<?php

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' : false)
{
	header("Content-Type: text/json; charset=utf-8");
	switch($_POST["type_action"])
	{
		case "add_option":								
			$r =& Registry::get("MDB")->query("INSERT INTO `".PRFX."cars_options` (`ID`,`Parent`,`Name`,`Text`,`Type`) VALUES ('', '".$_POST["parent_option"]."', '".$_POST["name_option"]."', '".$_POST["text_option"]."', '".$_POST["type_option"]."');");
			if (PEAR::isError($r)) {
				die($r->getMessage().' ::: '.$r->getUserInfo());
			}
			else
			{
				$json["metadata"] = array(
					"id"   => mysql_insert_id(),
					"name" => $_POST["name_option"],
					"text" => $_POST["text_option"]
				);
			}			
			exit(getJSON($json));
		break;
		
		case "delete_option":
			$r =& Registry::get("MDB")->query("DELETE FROM `".PRFX."cars_options` WHERE `ID` = '".$_POST["id_item"]."' LIMIT 1;");
			if (PEAR::isError($r)) {
				$json["error"] = $r->getMessage().' ::: '.$r->getUserInfo();
			}
			else
			{
				$r =& Registry::get("MDB")->query("OPTIMIZE TABLE `".PRFX."cars_options`;");
				if (PEAR::isError($r)) {
					die($r->getMessage().' ::: '.$r->getUserInfo());
				}
				$json["success"] = "Успешно удалено!";
			}
			exit(getJSON($json));
		break;
	}
}

class ControllerAdmin_Cars extends ControllerAdmin_Base
{
	public function __construct($section) {		
		$this->section      = $section;
		$this->common_vars  = Registry::get("common_vars");
		$this->table_module = PRFX."cars";		
	}
	
	public function init()
	{
		$this->pages = new structure($this->table_module);
		$this->pages->tpl = 'catalog.list.tpl';
		$this->pages->active_group = ($_GET["catalog_parent"] ? $_GET["catalog_parent"] : 0);
		$this->pages->mode = "cars";
		$this->pages->sorting = ' ORDER BY `Por`';
		$this->pages->field = array(						
			'edit'   => true,
			'por'    => true,
			'show'   => true,
			'delete' => true,			 
			'field_cfg' => array(
				array(
					'name'      => 'Название',
					'fieldname' => 'name',
					'width'     => '50%',
					'link'      => true,			
					'attr'      => false
				),
				array(
					'name'      => 'Системное имя',
					'fieldname' => 'sys_name',
					'width'     => '50%',
					'link'      => true,			
					'attr'      => false
				)
			),
			"aoData" => array(
				"bSortable" => array(
					"false",
					"false",
					"false",
					"false",
					"null",
					"null"
				)
			)
		);
	}
	
	public function addToTable()
	{						
		extract($_POST);		
		$last_modified = time();
		if ($_POST['type'] == 'add') {
			eval(functions::insert_sql($this->table_module, 'sql'));
			$r =& Registry::get("MDB")->query($sql);		
			if (PEAR::isError($r)) {
				die($r->getMessage().' ::: '.$r->getUserInfo());
			}
		}
		elseif($_POST['type'] == 'editt') {
			$name = htmlspecialchars($name);
			eval(functions::update_sql($this->table_module, 'sql', 'id', $_POST['id']));
			$r =& Registry::get("MDB")->query($sql);		
			if (PEAR::isError($r)) {
				die($r->getMessage().' ::: '.$r->getUserInfo());
			}
		}		
	}
	
    public function out()
	{
		self::init();
		if(!empty($_POST['type'])) {		
			self::addToTable();
		}
		
		if(empty($_GET['type'])) {
			$this->action = '<div class="addbuttons"><a href="?m=content&id='.$_GET["id"].'&parent='.$_GET["parent"].'&catalog_parent='.intval($_GET["catalog_parent"]).'&type=add" class="ui_wo_buttons ui-state-default ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Добавить запись</a></div>';			
			return $this->pages->FirstPage();
		}		
		else
		{
			if($_GET['type'] == 'edit')
			{							   
				$r =& Registry::get("MDB")->query("SELECT * FROM `".$this->table_module."` WHERE `ID`='".$_GET['catalog_id']."' LIMIT 1;");
				if (PEAR::isError($r)) {
					die($r->getMessage().' ::: '.$r->getUserInfo());
				}
				if($r->numRows()) {
					$Field = $r->fetchRow(MDB2_FETCHMODE_ASSOC);
				}
			}			
			elseif($_GET['type'] == 'add' || empty($_GET['type'])) {
				$Field["por"] = functions::incrPor($this->table_module, $this->pages->active_group);			
			}
			
			/* ID */
			if($this->pages->pInfo['auto_increment'] && empty($_GET['catalog_id'])) {
				$id_action = $this->pages->pInfo['auto_increment'];
			}
			elseif(!empty($_GET['catalog_id'])) {
				$id_action = $_GET['catalog_id'];
			}			
			
			/* Тип раздела */
			$l = new lists;		
			$l->type      = "select";
			$l->pid       = 38;
			$l->el_name   = 'section_type';
			$l->sel_value = $Field["section_type"];
			$section_type  = $l->processor();
	
			/**************************************************************************************/
			/**************************   DOWNLOADS PICTURE  **************************************/
			/**************************************************************************************/
			
			if(!empty($id_action)) 
			{
				/* По умолчанию (модель) */
				if(($Field["section_type"] == "default") || !$Field["section_type"])
				{
					//$l = new lists;
			
					/* Тип кузова */					
					/*$l->type      = "select";
					$l->pid       = 35;
					$l->el_name   = 'body';
					$l->sel_value = $Field["body"];
					$body_select  = $l->processor();*/
					
					/* Колво дверей */
					/*$l->type      = "select";
					$l->pid       = 37;
					$l->el_name   = 'doors';
					$l->sel_value = $Field["doors"];
					$doors_select  = $l->processor();*/				
					
					/* Фото модели */
					$IMAGE = ImgCrop::createUploadCode(array(
					  'text'           => 'Фото модели',
					  'idelem'         => $id_action,
					  'namefile'       => 'model_original.jpg',	 
					  'previews' => array(
						  array(
							 "namefile" => '200x98_model_trumbnail.jpg',
							 "textfile" => 'На главную моделей 200px × 98px',
							 "width"    => 200,
							 "height"   => 98,
							 "prefix"   => '200x98_model_trumbnail'
						  ),
						  array(
							 "namefile" => '280x152_model_trumbnail.jpg',
							 "textfile" => 'В шапку 280px × 152px',
							 "width"    => 280,
							 "height"   => 152,
							 "prefix"   => '280x152_model_trumbnail'
						  )
					  ),
					  'folder'         => "cars",
					  'limit'          => 1,
					  'prefix'         => 'model_original',
					  'processor'      => '/ajax/admin/upload.backend.php'
					))."<br /><hr />";
				}
				
				/* Обзор */
				elseif($Field["section_type"] == "review")
				{	
					/* Обзор :: Главный баннер */
					$IMAGE = ImgCrop::createUploadCode(array(
					  'text'           => 'Обзор :: Галерея (160px × 160px)',
					  'idelem'         => $id_action,
					  'namefile'       => 'review_original.jpg',	 
					  'previews'  => array(
						  array(
							 "namefile" => '160x160_review_trumbnail.jpg',
							 "textfile" => 'Галерея 160px × 160px',
							 "width"    => 160,
							 "height"   => 160,
							 "prefix"   => '160x160_review_trumbnail'
						  )
					  ),
					  'folder'         => "cars",
					  'limit'          => 20,
					  'prefix'         => 'review_original',
					  'processor'      => '/ajax/admin/upload.backend.php'
					))."<br /><hr />";
				}
		
				elseif($Field["section_type"] == "complete")
				{
					$l = new lists;
			
					/* Тип двигателя */					
					$l->type      = "radio";
					$l->pid       = 36;
					$l->el_name   = 'engine';
					$l->sel_value = $Field["engine"];
					$engine_radio  = $l->processor();					
					
					/* Комплектации :: Фото комплектации */
					$IMAGE.= ImgCrop::createUploadCode(array(
					  'text'           => 'Комплектации :: Фото оригинала (685px × 325px)',
					  'idelem'         => $id_action,
					  'namefile'       => 'complete_original.jpg',	 
					  'previews'  => array(	
					      array(
							 "namefile" => '137x65_complete_trumbnail.jpg',
							 "textfile" => 'Превью 137px × 65px',
							 "width"    => '137',
							 "height"   => '65',
							 "prefix"   => '137x65_complete_trumbnail'
						  ),				  
						  array(
							 "namefile" => '215x102_complete_trumbnail.jpg',
							 "textfile" => 'Превью 215px × 102px',
							 "width"    => '215',
							 "height"   => '102',
							 "prefix"   => '215x102_complete_trumbnail'
						  )
					  ),
					  'folder'         => "cars",
					  'limit'          => 1,
					  'prefix'         => 'complete_original',
					  'processor'      => '/ajax/admin/upload.backend.php'
					));
				}
				elseif($Field["section_type"] == "press")
				{
					$IMAGE = ImgCrop::createUploadCode(array(
					  'text'           => 'Пресса :: Фото',
					  'idelem'         => $id_action,
					  'namefile'       => 'press_original.jpg',	 
					  'previews'  => array(						  
						  array(
							 "namefile" => '215x102_press_trumbnail.jpg',
							 "textfile" => 'Превью 215px × 102px',
							 "width"    => '215',
							 "height"   => '102',
							 "prefix"   => '215x102_press_trumbnail'
						  )
					  ),
					  'folder'         => "cars",
					  'limit'          => 1,
					  'prefix'         => 'press_original',
					  'processor'      => '/ajax/admin/upload.backend.php'
					))."<br /><hr />";					
					
					$IMAGE.= File::getCode(array(
					  'text'           => 'Пресса :: Загрузка файла',
					  'id'             => $id_action,
					  'name'           => $Field["name"],
					  'postfix'        => 'documents_press',
					  'folder'         => "cars",
					  'limit'          => 1,
					  'prefix'         => 'documents_press'
					));
				}
				elseif($Field["section_type"] == "documents")
				{
					/* Документы :: Шапка */
					$IMAGE = ImgCrop::createUploadCode(array(
					  'text'           => 'Документы :: Шапка (960px × 150px)',
					  'idelem'         => $id_action,
					  'namefile'       => 'documents_head.jpg',
					  'folder'         => "cars",
					  'limit'          => 2,
					  'prefix'         => 'documents_head',
					  'processor'      => '/ajax/admin/upload.backend.php'
					))."<br /><hr />";
					
					/* Документы :: Превью документа */
					$IMAGE.= ImgCrop::createUploadCode(array(
					  'text'           => 'Документы :: Превью документа (56px × 78px)',
					  'idelem'         => $id_action,
					  'namefile'       => 'documents_original.jpg',	 
					  'previews'  => array(						  
						  array(
							 "namefile" => '56x78_documents_trumbnail.jpg',
							 "textfile" => 'Превью 56px × 78px',
							 "width"    => '56',
							 "height"   => '78',
							 "prefix"   => '56x78_documents_trumbnail'
						  )
					  ),
					  'folder'         => "cars",
					  'limit'          => 1,
					  'prefix'         => 'documents_original',
					  'processor'      => '/ajax/admin/upload.backend.php'
					))."<br /><hr />";
					
					$IMAGE.= File::getCode(array(
					  'text'           => 'Документы :: Загрузка файла',
					  'id'             => $id_action,
					  'name'           => $Field["name"],
					  'postfix'        => 'documents_tech_features',
					  'folder'         => "cars",
					  'limit'          => 1,
					  'prefix'         => 'documents_tech_features'
					));
					
				}
				elseif($Field["section_type"] == "gallery")
				{
					/* Обои рабочего стола */
					/*$IMAGE = ImgCrop::createUploadCode(array(
					  'text'           => 'Галерея :: Обои рабочего стола',
					  'idelem'         => $id_action,
					  'namefile'       => 'gallery_wallpaper_original.jpg',	 
					  'previews'  => array(
						  array(
							 "namefile" => '84x40_gallery_wallpaper_trumbnail.jpg',
							 "textfile" => 'Превью 84px × 40px',
							 "width"    => '84',
							 "height"   => '40',
							 "prefix"   => '84x40_gallery_wallpaper_trumbnail'
						  ),
						  array(
							 "namefile" => '1024x768_gallery_wallpaper.jpg',
							 "textfile" => '1024px × 768px',
							 "width"    => '1024',
							 "height"   => '768',
							 "prefix"   => '1024x768_gallery_wallpaper'
						  ),
						  array(
							 "namefile" => '1280x1024_gallery_wallpaper.jpg',
							 "textfile" => '1280px × 1024px',
							 "width"    => '1280',
							 "height"   => '1024',
							 "prefix"   => '1280x1024_gallery_wallpaper'
						  ) 
					  ),
					  'folder'         => "cars",
					  'limit'          => 25,
					  'prefix'         => 'gallery_wallpaper_original',
					  'processor'      => '/ajax/admin/upload.backend.php'
					))."<br /><hr />";*/
					
					/* Галерея */
					$IMAGE = ImgCrop::createUploadCode(array(
					  'text'           => 'Галерея',
					  'idelem'         => $id_action,
					  'namefile'       => 'gallery_original.jpg',	 
					  'previews'  => array(
						  array(
							 "namefile" => '_120x62_gallery_trumbnail.jpg',
							 "textfile" => 'Превью 120px × 62px',
							 "width"    => 120,
							 "height"   => 62,
							 "prefix"   => '120x62_gallery_trumbnail'
						  )  
					  ),
					  'folder'         => "cars",
					  'limit'          => 25,
					  'prefix'         => 'gallery_original',
					  'processor'      => '/ajax/admin/upload.backend.php'
					))."<br /><hr />";
				}
			}			
			/**************************************************************************************/
			/**************************   DOWNLOADS PICTURE  **************************************/
			/**************************************************************************************/
			
			/* Опции */
			if($Field["section_type"] == "complete")
			{
				$r =& Registry::get("MDB")->query("SELECT * FROM `".PRFX."cars_options` WHERE `Parent`='".$_GET['catalog_id']."' ORDER BY `ID`;");
				if (PEAR::isError($r)) {
					die($r->getMessage().' ::: '.$r->getUserInfo());
				}
				if($r->numRows()) {
					while($p = $r->fetchRow(MDB2_FETCHMODE_ASSOC)) {
						$option_list[$p["type"]][] = $p;
					}
				}				
			}
			
			
			//print_r($this->common_vars);
			Registry::get("smarty")->assign(array(
				'SECTION'      => $this->section,				
				'ID_ACTION'    => $id_action,
				'Field'        => $Field,
				'TABLE'        => $this->table_module,
				'IMAGE'        => $IMAGE,
				'BODY_SELECT'  => $body_select,
				'DOORS_SELECT' => $doors_select,
				'ENGINE_RADIO' => $engine_radio,
				'section_type' => $section_type				

				//'GROUPS'    => groups::get($this->table_module, $this->pages->active_group)
			));
			return Registry::get("smarty")->fetch(TEMPLATE_ADMIN.$this->common_vars["controller_template"], Registry::get("cache_id"));
		}		
    }
}

$controller = new ControllerAdmin_Cars($section);
$ob_admin_out = $controller->out();
$ob_admin_action = $controller->action;

$catalog_parent = $_GET["catalog_parent"] ? $_GET["catalog_parent"] : 0;
$ob_left_menu_catalog = new catalog_tree($controller->table_module);
$ob_left_menu_catalog->registry_parent_id($catalog_parent);
$left_menu_catalog = $ob_left_menu_catalog->getMenu(0, 0, $catalog_parent);

?>